<?php

// +----------------------------------------------------------------------
// | 支付宝处理
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\controller\api\notify;

use alipay\Trade;
use app\pay\event\Pay as PayEvent;
use think\facade\Config;
use think\facade\Env;
use app\event\ucenter\User as UserEvent;
use think\facade\Log;
use wechat\mch\Pay as WechatMchPay;
use app\pay\model\Payment as PaymentModel;
use app\model\pay\Pay as PayModel;
use app\model\ucenter\User as UserModel;
use app\event\pos\PosOrder as PosOrderEvent;
use app\event\app\ExchangeCoupon as ExchangeCouponEvent;
use app\event\app\ThirdRecharge as ThirdRechargeEvent;
use app\event\store\Order as OrderEvent;

class Pay extends Common
{


    /**
     * @return string|void
     * 'gmt_create' => '2024-10-08 14:26:12',
     * 'charset' => 'UTF-8',
     * 'seller_email' => '2098557710@qq.com',
     * 'subject' => 'vip',
     * 'sign' => 'cU9FMIWpmZURyhoXsAtbzrEfi636wejDWzduxpM6MlsLhm2SSJFUxyI2GY4OEMrVeVF/5ns88tghBI8JBv0csADHduq+/Xz3Cm/XEIJ8HzpeF9afYrRnQMNi1PUZO6kFaAugiYg5dpNnYFGwUUHWG3elX/LiiogRnwFHRek27t66pOZpPLFWbghH5WoERSP7s/wyBRsrfwjUu6+QZHmXRCOlafvWG1r1rP3VDXj5dw6sjVBE19y8OvVLVwnwllEtHCre01ZNT4z5fnbWJDWceVn+vD8+v5JZre15ngqnAaMB1L2Xqo2I+1Xonzl36ZPiyi/+7jtGM7kNeXr7kk7TeQ==',
     * 'buyer_open_id' => '0297AUyntXQuJMjY8gZdGsgRlRYQXNHg4a5tiG2FUCK2r4b',
     * 'invoice_amount' => '0.01',
     * 'notify_id' => '2024100801222142614022291499611202',
     * 'fund_bill_list' => '[{&quot;amount&quot;:&quot;0.01&quot;,&quot;fundChannel&quot;:&quot;ALIPAYACCOUNT&quot;}]',
     * 'notify_type' => 'trade_status_sync',
     * 'trade_status' => 'TRADE_SUCCESS',
     * 'receipt_amount' => '0.01',
     * 'app_id' => '2021004181661289',
     * 'buyer_pay_amount' => '0.01',
     * 'sign_type' => 'RSA2',
     * 'seller_id' => '2088941431977212',
     * 'gmt_payment' => '2024-10-08 14:26:13',
     * 'notify_time' => '2024-10-08 14:51:17',
     * 'merchant_app_id' => '2021004181661289',
     * 'passback_params' => 'merchantBizType%3d3C%26merchantBizNo%3d2016010101111',
     * 'version' => '1.0',
     * 'out_trade_no' => '1728368763',
     * 'total_amount' => '0.01',
     * 'trade_no' => '2024100822001422291434009655',
     * 'auth_app_id' => '2021004181661289',
     * 'buyer_logon_id' => '139****7675',
     * 'point_amount' => '0.00',
     */
    public function alipay()
    {
        if ($this->request->param('out_trade_no', '')) {
            // 支付成功
            $param = $this->request->except(['controller', 'action']);
            file_put_contents('./alipaynotify.txt', '信息收到 :' . json_encode($param) . "\r\n\r\n", FILE_APPEND);
            if (check_alipay($param)) {
                $pay = PayModel::where('pay_sn', $param['out_trade_no'])->find();
                if ($pay) {
                    $pay['api_amount'] = $param['total_amount'];
                    if (isset($param['refund_fee'])) {
                        $pay['refund_money'] = $param['refund_fee'];
                    }
                    $pay['api_buyer_id'] = $param['buyer_logon_id'];
                    $pay['api_pay_status'] = $param['trade_status'];
                    $pay['api_pay_no'] = $param['trade_no'];
                    $pay['appid'] = $param['auth_app_id'];
                    if ($pay['refund_money'] == 0 && $pay['api_pay_status'] == 'TRADE_SUCCESS' || $pay['api_pay_status'] == 'TRADE_FINISHED') {
                        $pay['status'] = 1;
                        $pay['pay_time'] = time_format();
                        if ($pay->save()) {
                            $this->_dealPay($pay);
                        } else {
                            return 'FAIL';
                        }
                    } elseif ($pay['api_pay_status'] == 'TRADE_CLOSED') {
                        $pay['status'] = -1;
                        $pay['gmt_close'] = $param['gmt_close'];
                        if ($pay->save()) {
                            return 'SUCCESS';
                        }
                    } else {

                        return 'FAIL';
                    }
                    return 'SUCCESS';
                } else {
                    return 'FAIL';
                }

            } else {
                return 'SUCCESS';
            }
            Log::write('支付宝异步信息：' . var_export($param, true));
        } else {
            Log::write('支付宝异步信息验证失败');
            return 'FAIL';
        }
    }


    public function tet()
    {
//        $pay = PayModel::where('id','942')->find();
//
//        dump($this->_dealPay($pay));
    }

    /**
     * 支付宝预授权
     * @return string|void
     * 'gmt_create' => '2025-01-20 09:45:19',
     * 'charset' => 'UTF-8',
     * 'operation_type' => 'FREEZE',
     * 'sign' => 'Y0n3MpR7j6RoJgdEeeSUvNV49L31x914hESk5An+zP1En9XbQzR7BlbtvUk8VRukJpQZcL008RrtkT99dKyWOCG934905FbGy5POm9XCnUpxot3RaQbdeH9QkGHynUBDwNa/lAvZaiQ8VvnxtJkZ1uk/8ApjMkOxhaelZ1fL7QHpbg8eEK0muERx4O8D0pQ2IaSAbWlwVzdhjorb8mG/O1B6w4xBdOMXc8Ejw5NrCeiAXqoOmj88N/ZlUAF4NIdjemWV6WWg4qlGGkbe3LCFJHotJ8xjDvkdhpzD6mKvOaIaWMKXMTgMcKbYEPAOyr2Fve8DMtTrufyYgno63Es/Ng==',
     * 'auth_no' => '2025012010002001170599704078',
     * 'notify_id' => '2025012001222094529099041484205266',
     * 'notify_type' => 'fund_auth_freeze',
     * 'gmt_trans' => '2025-01-20 09:45:29',
     * 'operation_id' => '20250120699319131705',
     * 'out_request_no' => '9183600760156',
     * 'app_id' => '2021004181661289',
     * 'sign_type' => 'RSA2',
     * 'amount' => '0.10',
     * 'rest_amount' => '0.10',
     * 'notify_time' => '2025-01-20 09:45:29',
     * 'out_order_no' => '9183600760156',
     * 'merchant_app_id' => '2021004181661289',
     * 'version' => '1.0',
     * 'total_pay_amount' => '0.00',
     * 'payer_open_id' => '0177AUyntXQuJMjY8gZdGsgRmlcCntiff8ZR0ljTZ9S0AQe',
     * 'total_freeze_amount' => '0.10',
     * 'auth_app_id' => '2021004181661289',
     * 'total_unfreeze_amount' => '0.00',
     * 'status' => 'SUCCESS',
     * 'payer_logon_id' => 'lil***@163.com',
     * 'controller' => 'pay',
     * 'action' => 'alipay',
     */
    public function freeze()
    {
        if ($this->request->param('out_order_no', '')) {
            // 支付成功
            $param = $this->request->except(['controller', 'action']);
            file_put_contents('./alipaynotify.txt', '信息收到 :' . json_encode($param) . "\r\n\r\n", FILE_APPEND);
            if (check_alipay($param)) {
                $pay = PayModel::where('pay_sn', $param['out_order_no'])->find();
                if ($pay) {
                    $pay['api_amount'] = $param['total_freeze_amount'];
                    $pay['operation_type'] = $param['operation_type'];
                    $pay['api_pay_status'] = $param['status'];
                    $pay['auth_no'] = $param['auth_no'];
                    $pay['appid'] = $param['auth_app_id'];
//                    $pay['api_buyer_id'] = $param['buyer_logon_id'];
                    if ($pay['api_pay_status'] == 'SUCCESS') {
                        $pay['status'] = 1;
                        $pay['pay_time'] = time_format();
                        if ($pay->save()) {
                            $this->_dealPay($pay);
                        } else {
                            return 'FAIL';
                        }
                    } else {

                        return 'FAIL';
                    }
                    return 'SUCCESS';
                } else {
                    return 'FAIL';
                }

            } else {
                return 'SUCCESS';
            }
            Log::write('支付宝异步信息：' . var_export($param, true));
        } else {
            Log::write('支付宝异步信息验证失败');
            return 'FAIL';
        }
    }

    public function unfreeze()
    {
//        dump(alipay_app_h5_pre_pay(time(), 1, '授权', $type = 'vip'));
//        exit();
        $pay = PayModel::where('id', 1138)->find();
//        $pay['action_no'] = $pay['action_no']+1;
//        $pay->save();

//        $this->_dealPay($pay);
//        alipay_app_unfreeze_pay($pay,0.02,'退钱');
//        $pay['action_no'] = $pay['action_no'] + 1;
//        alipay_app_unfreeze_pay($pay, $pay['api_amount'], '订单取消自动退费');
//        $pay['status'] = -1;
////        alipay_app_freeze_pay($pay, $pay['total_amount'], $pay['title']);
//        $pay->save();

        dump($pay->toArray());
    }

    protected function _dealPay($pay)
    {
        if ($pay['type'] == 'deposit') {
            $user = UserModel::where('id', $pay['user_id'])->find();
            if ($user['level'] != 2) {
                $user['level'] = 2;
                $user['deposit'] = $pay['total_amount'] + $user['deposit'];
                $user->save();
                if ($user['is_effective'] != 1) {
                    $user['is_effective'] = 1;
                    UserEvent::setEffective($user['id']);
                } else {
                    UserEvent::levelUp($user['id']);
                }
            }
            // 开通vip
            Log::write('开通VIP1');
        } elseif ($pay['type'] == 'vip') {
            $user = UserModel::where('id', $pay['user_id'])->find();
            $user['level'] = 2;
            $user->save();
            // 开通vip
            Log::write('开通VIP');
        } elseif ($pay['type'] == 'pos') {
            Log::write('购买pos');
            $event = new PosOrderEvent();
            $event->pay($pay);
        } elseif ($pay['type'] == 'exchange') {
            Log::write('购买会员券');
            $event = new ExchangeCouponEvent();
            $event->pay($pay);
        } elseif ($pay['type'] == 'life') {
            Log::write('生活缴费');
            $event = new ThirdRechargeEvent();
            $re = $event->pay($pay);
        } elseif ($pay['type'] == 'order') {
            Log::write('商城');
            $event = new OrderEvent();
            $re = $event->pay($pay);
        } else {
            // 开通vip
            Log::write('未知');
        }
        return $pay;
    }

    public function refund()
    {
        $pay = \app\pay\model\Pay::where('id', 334)->find();
        // 支付成功
        $event = new PayEvent();
        $result = $event->refund($pay);
        dump($result);
        Log::write('支付宝异步信息：' . var_export($result, true));

    }

    public function h5()
    {
        $pay = PayModel::where('pay_sn', $this->request->param('pay_sn'))->where('status', 0)->find();
        if ($pay) {
            if ($pay['user_id'] == 16006 || $pay['user_id'] == 16013) {
                return alipay_h5_pay($pay['pay_sn'], 0.03, $pay['title'], $pay['type']);
            } else {
                return alipay_h5_pay($pay['pay_sn'], $pay['total_amount'], $pay['title'], $pay['type']);
            }
        } else {
            return 'fail';
        }
    }


    public function transfer()
    {
        $pay = \app\pay\model\Pay::where('id', 334)->find();
        // 支付成功
        $event = new PayEvent();
        $result = $event->transferAlipay('alipay_web', time(), 'lilwil@163.com', 0.01, '刘伟');
        dump($result);
        Log::write('支付宝异步信息：' . var_export($result, true));

    }


    /**
     * @return string
     * 'appid' => 'wx7c83e79f78fdfa10',
     * 'attach' => 'pos',
     * 'bank_type' => 'SPDB_CREDIT',
     * 'cash_fee' => '1',
     * 'device_info' => 'app',
     * 'fee_type' => 'CNY',
     * 'is_subscribe' => 'N',
     * 'mch_id' => '1697093647',
     * 'nonce_str' => 'l4dPAMkBP7m9jFpM9Ih1HZ7M3GvsZ8up',
     * 'openid' => 'oaD6V6U8fBP-r-9X4JEtLxU9oFhg',
     * 'out_trade_no' => '1178605571108',
     * 'result_code' => 'SUCCESS',
     * 'return_code' => 'SUCCESS',
     * 'sign' => '6F105AD8395A92DA7ADF4DAFFE85DD4C',
     * 'time_end' => '20241123141215',
     * 'total_fee' => '1',
     * 'trade_type' => 'APP',
     * 'transaction_id' => '4200002453202411237081014747',
     */
    public function wechat()
    {
        $WechatMchPay = new WechatMchPay('wx7c83e79f78fdfa10', '1697093647', 'qC04wNxXUFVv2eEItzWpdb8BSPMTkHln');
        $data = $WechatMchPay->saveData(file_get_contents('php://input'));
        file_put_contents('./wxpaynotify.txt', '信息收到 :' . json_encode($data) . "\r\n\r\n", FILE_APPEND);
        Log::record($data);
        if ($WechatMchPay->checkSign()) {
            $pay = PayModel::where('pay_sn', $data['out_trade_no'])->where('payment_code', 'wxpay')->find();
            if ($pay) {
                $pay['api_amount'] = $data['total_fee'] / 100;
                $pay['api_buyer_id'] = $data['openid'];
                $pay['api_pay_status'] = $data['result_code'];
                $pay['api_pay_no'] = $data['transaction_id'];
                $pay['appid'] = $data['appid'];
                if ($pay['api_pay_status'] == 'SUCCESS') {
                    $pay['status'] = 1;
                    $pay['pay_time'] = time_format();
                    if ($pay->save()) {
                        $this->_dealPay($pay);
                    }
                }
                $WechatMchPay->setReturnParameter('return_code', 'SUCCESS'); // 设置返回码
                $WechatMchPay->setReturnParameter('return_msg', 'OK'); // 返回信息
            } else {

                $WechatMchPay->setReturnParameter('return_code', 'FAIL'); // 返回状态码
                $WechatMchPay->setReturnParameter('return_msg', '订单不存在'); // 返回信息
            }

        } else {
            $WechatMchPay->setReturnParameter('return_code', 'FAIL'); // 返回状态码
            $WechatMchPay->setReturnParameter('return_msg', '签名失败'); // 返回信息
            Log::record('微信验证签名失败：' . var_export($data, true));
        }
        Log::record('返回' . $WechatMchPay->returnXml());
        return $WechatMchPay->returnXml();
    }
}
